module(..., package.seeall)

require'zdc.node'
require'zdc.typeex'
require'zdc.dpl'
require'zdc.idutil'

Gim = {}
local Gim_mt = {__metatable={}, __index=Gim}

function new()
	local repo = setmetatable({map={}}, Gim_mt)
	return repo
end

function Gim:_delall()
	self.map={}
end
function Gim:_get_info()
	local re={}
	local m=self.map
	for i=1,#m do
		local t=m[i]
		local ty=type(t[1])
		if ty=='string' then
			table.insert(re,{rootid=ty,dpl=t[4]})
		elseif ty=='function' then
			table.insert(re,{rootid='?',dpl=t[4]})
		else
			error('unknow dpl id pattern: ' .. tostring(t[1]))
		end
	end
	return re
end

--return dpl[,errmsg]
function Gim:_add_dpl(dal,idpat,childpat,subpat,dpl)
	table.insert(self.map,{idpat,childpat,subpat,dpl})
	return dpl
end

function Gim:_get_svcdpl_by_id(dal,id)
	local dpl=self:_get_dpl_by_id(dal,id)
	if dpl then return dpl end
end

--return dpl[,errmsg]
function Gim:_get_dpl_by_id(dal,id)
	if not id then return nil end
	local m=self.map
	for i=1,#m do
		local t=m[i]
		local ty=type(t[1])
		if ty=='string' then
			if id==t[1] or zdc.idutil.IsRoot(t[1],id) then return t[4] end
		elseif ty=='function' then
			if t[1](id) then return t[4] end
		else
			error('unknow dpl id pattern: ' .. tostring(t[1]))
		end
	end
	return nil
end

function Gim:_get_dpl_by_parent(dal,idparent)
	local m=self.map
	local idparent_=idparent .. '/'
	for i=1,#m do
		local t=m[i]
		local ty=type(t[2])
		if ty=='string' then
			if string.sub(idparent_,1,#t[2])==t[2] then return t[4] end
		elseif ty=='function' then
			if t[2](idparent) then return t[4] end
		else
			error('unknow dpl id pattern: ' .. tostring(t[1]))
		end
	end
	return nil
end

--return {dpl1,dpl2,...}
function Gim:_get_sub_dpls(dal,idparent)
	local re={}
	local m=self.map
	local idparent_=idparent .. '/'
	for i=1,#m do
		local t=m[i]
		local ty=type(t[3])
		if ty=='string' then
			if string.sub(idparent_,1,#t[3])==t[3] then table.insert(re,t[4]) end
		elseif ty=='function' then
			if t[3](idparent) then table.insert(re,t[4]) end
		else
			error('unknow dpl id pattern: ' .. tostring(t[1]))
		end
	end
	return re
end

--when match call fun(dpl)
function Gim:_do_every_dpl(dal,fun)
	local m=self.map
	for i=1,#m do
		local r1,r2,r3=fun(m[i][4])
		if r1 then return r1,r2,r3 end
	end
end
